package netty.netty01.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @author ZH
 * Date: 2022/6/8
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                //添加EventLoop
                .group(group)
                //添加channel
                .channel(NioSocketChannel.class)
                //添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    //在链接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder()); //String编码
                    }
                })
                .connect("127.0.0.1", 8080);

        // 1. 同步  当前线程阻塞, 等待链接建立完成后,再发送数据
        ChannelFuture future = channelFuture.sync();
        Channel channel = future.channel();

        new Thread(() -> {
            Scanner sc = new Scanner(System.in);
            while (true){
                String input = sc.nextLine();
                if (input.equals("q")){
                    channel.close();
                    break;
                }else {
                    channel.writeAndFlush(input);
                }
            }
        },"input").start();

        //2. 异步  添加一个Listener
    /*    channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();

            }
        });*/

    //3 异步关闭channel 并且退出group
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener((ChannelFutureListener) future2 -> {
            log.info("关闭channel....");
            group.shutdownGracefully();
        });
    }
}
